#!/usr/local/bin/python2.5

_Copyright = "Copyright @ 2010 Michael P. Reilly. All rights reserved."
_SCM_ID = "$Id: admin.py 87 2010-12-17 03:45:00Z arcege@gmail.com $"

from kcapp.app import logging, main
from kcapp.tools import valid_name, update_image_md5
from kcapp.reqhandler import AdminRequestHandler
from kcapp.database import OSDBSeed, OSDBTypes, OSDBImage

DefaultType = 'Default'

class MainPage(AdminRequestHandler):
    template_name = 'main'
    help_url = 'admin'

Stock_images = (
    ('stock00', '8e4d942a42f8c41457b5e1686126d0c2'),
    ('stock01', 'e14e06d962a3135979c6dd4f9afc168f'),
    ('stock02', '6e3eec4d3d04d07322ede54d9fdd1706'),
    ('stock03', 'c5023b525e306a03a189720d3d50ae73'),
    ('stock04', 'c2f00cbb7ce1e4b539b6f5570f35d352'),
    ('stock05', '249002d93e5186737a69c86572708b29'),
    ('stock06', '220a432fc0d6d1ffb7131f7c0a44c3c7'),
    ('stock07', '0edf24884efcf6cf1061ee2c063a5905'),
)

class DbInitPage(AdminRequestHandler):
    template_name = 'dbinit'
    def process_request(self):
        self.vars['body'] = []
        query = OSDBTypes.all()
        query.filter('name =', DefaultType)
        c = query.count()
        if c == 0:
            entry = OSDBTypes(name=DefaultType, comment='Default type')
            entry.put()
            self.vars['body'].append('Added &quot;Default&quot; type')
        else:
            entry = query.get()
            if entry.comment != 'Default type':
                entry.comment = 'Default type'
                entry.put()
                self.vars['body'].append(
                    'Update &quot;%s&quot; type' % DefaultType
                )
        from kcapp.database import StockMd5s
        query = StockMd5s.all()
        for e in query:
            self.vars['body'].append(
                'Delete stock image &quot;%s&quot; from database' % e.iname
            )
            e.delete()
        for n, m in Stock_images:
            logging.warn('Handling stock image md5 %s' % repr((n, m)))
            img = StockMd5s(iname=n, md5=m)
            img.put()
            self.vars['body'].append(
                'Add stock image &quot;%s&quot; to database' % n
            )
        query = StockMd5s.all()
        query.filter('iname =', False)
        for entry in query:
            try:
                update_image_md5(entry, self.request.url, force=True)
            except ValueError, e:
                self.vars['body'].append(
                    'Could not update md5 for &quot;%s;&quot;<br/>\n' +
                    '<blockquote>%s</blockquote>' % e
                )
            except Exception, e:
                self.vars['body'].append(
                    ('<span style="color:red;">Error: %s<br/>\n' +
                     '<blockquote>%s</blockquote>') % (entry.iname, e)
                )
                #self.send_msg(str(e), error=True)
                #raise self.Redirect('/admin')
            else:
                self.vars['body'].append(
                    'Update md5 for &quot;%s&quot;' % entry.iname
                )

class TypesPage(AdminRequestHandler):
    template_name = 'type_main'
    def process_request(self):
        query = OSDBTypes.all()
        query.order("name")
        self.vars['typeset'] = types = []
        for result in query:
            logging.warn('found type %s' % repr(result.name))
            types.append( (result.name, result.comment) )

class TypesNewPage(AdminRequestHandler):
    template_name = 'type_new'

class TypesNewSubmissionPage(AdminRequestHandler):
    template_name = None
    def process_request(self):
        if self.request.get('submit') == 'Submit':
            tname = str(self.request.get('tname'))
            if not valid_name(tname):
                self.send_msg('invalid type name', error=True)
                raise self.Redirect('/admin/type')
            comment = str(self.request.get('comment'))
            q = OSDBTypes.all()
            q.filter('name =', tname)
            if q.count() == 1:
                self.send_msg('this type already exists', error=True)
                raise self.Redirect('/admin/type')
            type = OSDBTypes(name=tname, comment=comment)
            key = type.put()
            logging.warn('creating type (%s, %s) => %s' % (repr(type.name), repr(type.comment), repr(key)))
        raise self.Redirect('/admin/type')

class TypesEditPage(AdminRequestHandler):
    template_name = 'type_edit'
    def process_request(self, tname):
        if tname == DefaultType:
            self.send_msg('unable to edit %s type' % DefaultType)
            raise self.Redirect('/admin/type')
        q = OSDBTypes.all()
        q.filter('name =', tname)
        if q.count() != 1:
            self.send_msg('more than one type entry', error=True)
            raise self.Redirect('/admin/type')
        itype = q.get()
        self.vars['tname'] = itype.name
        self.vars['comment'] = itype.comment

class TypesEditConfirmPage(AdminRequestHandler):
    template_name = None
    def process_request(self):
        req = str(self.request.get('submit'))
        tname = str(self.request.get('tname'))
        ntname = str(self.request.get('ntname'))
        comment = str(self.request.get('comment'))
        if tname == DefaultType:
            self.send_msg('unable to edit %s type' % DefaultType)
            raise self.Redirect('/admin/type')
        if req == 'Remove':
            raise self.Redirect('/admin/type/remove/%s' % tname)
        elif req == 'Edit':
            q = OSDBTypes.all()
            q.filter('name =', tname)
            if q.count() != 1:
                self.send_msg('more than one type entry', error=True)
                raise self.Redirect('/admin/type')
            type = q.get()
            dirty = False
            assert type.name == tname, 'Invalid data'
            if tname != ntname:
                if not valid_name(ntname):
                    self.send_msg('invalid type name', error=True)
                    raise self.Redirect('/admin/type')
                type.name = ntname
                dirty = True
            if type.comment != comment:
                type.comment = comment
                dirty = True
            if tname != ntname:
                # rename the type in each DB entry
                r = OSDBSeed.all()
                r.filter('type =', tname)
                for entry in r:
                    entry.type = ntname
                    entry.put()
            if dirty:
                type.put()
            logging.warn('updated %s' % repr(tname))
        raise self.Redirect('/admin/type')

class TypesRemovePage(AdminRequestHandler):
    template_name = None
    def process_request(self, tname):
        if tname == DefaultType:
            self.send_msg('unable to remove %s type' % DefaultType)
            raise self.Redirect('/admin/type')
        q = OSDBTypes.all()
        q.filter('name =', tname)
        if q.count() != 1:
            self.send_msg('more than one type entry', error=True)
            raise self.Redirect('/admin/type')
        type = q.get()
        r = OSDBSeed.all()
        r.filter('type =', tname)
        for entry in r:
            entry.type = 'Default'
            entry.put()
        type.delete()
        logging.warn('removed %s' % repr(tname))
        raise self.Redirect('/admin/type')

URL_Map = [
  ('/admin', MainPage),
  ('/admin/dbinit', DbInitPage),
  ('/admin/type', TypesPage),
  ('/admin/type/new', TypesNewPage),
  ('/admin/type/new/submission', TypesNewSubmissionPage),
  ('/admin/type/edit/confirm', TypesEditConfirmPage),
  ('/admin/type/edit/(.*)', TypesEditPage),
  ('/admin/type/remove/(.*)', TypesRemovePage),
]

if __name__ == "__main__":
    main(URL_Map)

